<template>
  <div class="step3-action-form">
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item :label="$t('system.actionmanage.modal.form.type')">
          <a-select :value="2" disabled>
            <a-select-option v-for="item in typeList" :key="item.value">
              {{ $t(item.label) }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item :label="$t('system.actionmanage.modal.form.id')">
          <a-input v-decorator="['BreachActionIdTag']" disabled />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item :label="$t('user.verification-code.required111566172')">
          <a-input
            v-decorator="['BreachActionName']"
            :placeholder="$t('user.verification-code.required111566172')"
            :disabled="!ifCanEdit"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-form-item
      style="margin: 0"
      :label="$t('user.verification-code.required111566173')"
      :label-col="{ span: lang ? 4 : 5 }"
      :wrapper-col="{ span: lang ? 20 : 19 }"
    >
      <a-textarea
        :auto-size="{ minRows: 3, maxRows: 10 }"
        :placeholder="$t('user.verification-code.required11156617311')"
        :rows="3"
        :disabled="!ifCanEdit"
        v-decorator="['BreachActionInfo']"
      />
    </a-form-item>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item
          :label="
            $t('breach.steps.step3.table.starttime')
          "
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-date-picker
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="$t('user.verification-code.required111566157')"
            :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
            v-decorator="[
              'BreachActionStartTime',
              {
                initialValue: moment().format('YYYY-MM-DD HH:mm:ss'),
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step1.content.form.tip1'),
                  },
                ],
              },
            ]"
            :disabled="!ifCanEdit"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item
          :label="$t('user.verification-code.required111566170')"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-date-picker
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="$t('user.verification-code.required111566157')"
            :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
            v-decorator="['BreachActionFinishTime']"
            :disabled="!ifCanEdit"
            :disabled-date="disabledDate"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <label class="self-label">
      {{ $t("user.verification-code.required111566178") }}:
    </label>
    <a-timeline>
      <a-timeline-item v-for="item in inputList" :key="item.Id">
        <a-space size="0" align="center">
          <p style="min-width: 150px">
            {{
              getActionTitle(item.ActionTitle)
                ? getActionTitle(item.ActionTitle) + " - "
                : ""
            }}
            {{ item.ActionCreateUserName || actionCreateUser }}
            {{ item.ActionCreatetime }}
          </p>
          <a-button
            type="link"
            @click="saveRemarkList([item])"
            :disabled="!ifCanEdit"
            v-if="
              item.ActionCreateUser === $store.state.user.info.userid &&
              item.ActionDelete !== 2
            "
            >{{ $t("user.verification-code.required1166") }}
          </a-button>
          <a-button
            type="link"
            @click="deleteInput(item.Id)"
            :disabled="!ifCanEdit"
            v-if="
              item.ActionCreateUser === $store.state.user.info.userid &&
              item.ActionDelete !== 2
            "
            >{{ $t("app.setting.copy") }}</a-button
          >
        </a-space>
        <a-form-item>
          <a-form-item>
            <a-textarea
              :auto-size="{ minRows: 3, maxRows: 10 }"
              :placeholder="$t('user.verification-code.required111566182')"
              :rows="3"
              :disabled="
                !ifCanEdit ||
                item.ActionCreateUser !== $store.state.user.info.userid ||
                item.ActionDelete === 2
              "
              v-model="item.ActionRemarkInfo"
            />
          </a-form-item>
        </a-form-item>
      </a-timeline-item>
      <div class="buttons">
        <a-button :disabled="!ifCanEdit" @click="addInput"
          >{{ $t("user.verification-code.required1115661106888") }}
        </a-button>
      </div>
    </a-timeline>
    <label class="self-label">
      {{ $t("user.verification-code.required111566110577294") }}:
    </label>
    <br />
    <div class="upload-files">
      <a-upload
        name="file"
        :remove="delFile"
        :file-list="fileLists"
        :multiple="true"
        :customRequest="handleChange"
        :disabled="!ifCanEdit"
      >
        <a-button icon="upload" :disabled="!ifCanEdit">
          {{ $t("user.verification-code.required111566163") }}
        </a-button>
      </a-upload>
      <span :style="{ left: lang ? '124px' : '146px' }">{{
        $t("breach.steps.step1.content.form.file.canupload")
      }}</span>
    </div>
    <a-row
      :gutter="24"
      class="mt-[10px]"
      v-if="
        (status === 1 || status === 3) &&
        (role.includes('processor') || role.includes('shareEdit'))
      "
    >
      <a-col :span="lang ? 12 : 20">
        <a-form-item :label="$t('breach.steps.step3.action.new.owner')">
          <a-select
            :placeholder="$t('breach.steps.step3.action.new.owner')"
            v-decorator="[
              'BreachActionUserId',
              {
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step3.action.new.owner'),
                  },
                ],
              },
            ]"
            show-search
            :disabled="!ifCanEdit"
            @search="(...rest) => getBmwUserList(...rest, 'bmwUserList')"
          >
            <a-select-option
              v-for="item in bmwUserList"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <div class="if-div">
      <template v-if="status === 1 || status === 3">
        <a-row :gutter="24">
          <a-col :span="20">
            <a-form-item
              :label="$t('breach.steps.step3.action.new.approve')"
              :label-col="{ span: lang ? 7 : 14 }"
              :wrapper-col="{ span: lang ? 17 : 10 }"
            >
              <a-radio-group
                v-decorator="[
                  'BreachActionDcoChoice',
                  {
                    initialValue: true,
                    rules: [
                      {
                        required: true,
                        message: $t('breach.steps.step1.content.form.tip1'),
                      },
                    ],
                  },
                ]"
                :disabled="!ifCanEdit"
                @change="(e) => (ifApprove = e.target.value)"
              >
                <a-radio :value="2">{{
                  $t("user.verification-code.requiredLuck11no")
                }}</a-radio>
                <a-radio :value="1">{{
                  $t("user.verification-code.requiredLuck11yes")
                }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="ifApprove === 1">
          <a-col :span="14">
            <a-form-item
              :label="$t('breach.steps.step3.action.new.approver')"
              :label-col="{ span: lang ? 7 : 12 }"
              :wrapper-col="{ span: lang ? 17 : 12 }"
            >
              <a-select
                :placeholder="$t('breach.steps.step3.action.new.approver')"
                v-decorator="[
                  'BreachActionDcoId',
                  {
                    rules: [
                      {
                        required: true,
                        message: $t('breach.steps.step3.action.new.approver'),
                      },
                    ],
                  },
                ]"
                show-search
                @search="(...rest) => getBmwUserList(...rest, 'userList')"
                :disabled="!ifCanEdit"
              >
                <a-select-option
                  v-for="item in userList"
                  :value="item.value"
                  :key="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </template>
      <div v-else class="mb-[10px]">
        {{ actionDetails.actionResult.user }}&nbsp;
        {{ actionDetails.actionResult.time }}
      </div>
      <a-form-item
        v-if="
          status !== 1 &&
          (status !== 3 || (status === 3 && role.includes('owner')))
        "
        :label="$t('breach.steps.step3.actionlist.result')"
        :label-col="{ span: lang ? 5 : 6 }"
        :wrapper-col="{ span: lang ? 19 : 18 }"
      >
        <a-textarea
          :auto-size="{ minRows: 3, maxRows: 10 }"
          :placeholder="$t('breach.steps.step1.content.form.tip')"
          :rows="3"
          :disabled="!ifCanEdit || status === 2 || status === 4"
          v-decorator="[
            'BreachActionResult',
            {
              rules: [
                {
                  required: true,
                  message: $t('breach.steps.step1.content.form.tip'),
                },
              ],
            },
          ]"
        />
      </a-form-item>
    </div>
    <div class="if-div"
      v-if="
        status === 2 || 
        (
          status === 4 &&
          actionDetails.approveResult.user &&
          actionDetails.BreachActionDcoChoice === 1
        )
      ">
      <div class="mb-[10px]">
        {{
          status === 2 ? actionCreateUser : actionDetails.approveResult.user
        }}&nbsp;
        {{
          status === 2
            ? moment().format("YYYY-MM-DD HH:mm:ss")
            : actionDetails.approveResult.time
        }}
      </div>
      <a-row :gutter="24">
        <a-col :span="14">
          <a-form-item :label="$t('breach.steps.step3.actionlist.approve')">
            <a-radio-group
              v-decorator="[
                'BreachActionDcoStatus',
                {
                  initialValue: true,
                  rules: [
                    {
                      required: true,
                      message: $t('breach.steps.step1.content.form.tip1'),
                    },
                  ],
                },
              ]"
              :disabled="!ifCanEdit"
              @change="(e) => $emit('changeProp', 'ifAgree', e.target.value)"
            >
              <a-radio :value="1">{{
                $t("breach.steps.step3.actionlist.approve.agree")
              }}</a-radio>
              <a-radio :value="2">{{
                $t("breach.steps.step3.actionlist.approve.disagree")
              }}</a-radio>
            </a-radio-group>
            <a-tooltip placement="right">
              <span slot="title">
                {{ $t("breach.steps.step3.actionlist.approve.tip") }}
              </span>
              <a-icon type="question-circle" />
            </a-tooltip>
          </a-form-item>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import { typeList } from "@/staticLists/breach";
import moment from "moment";
import axios from "axios";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { DcoQuery, getUserList, userQuerySearch } from "@/api/common/form";
import { createRemark, updateRemark } from "@/api/dataBreach/json";
import { deleteRemark, getActionRemarkList } from "@/api/dataBreach/form";
export default {
  name: "step3ActionForm",
  props: [
    "ifCanEdit",
    "lang",
    "status",
    "actionDetails",
    "ifAgree",
    "role",
    "form",
    "currentData",
    "initBmwList",
  ],
  data() {
    return {
      typeList,
      inputList: [],
      actionCreateUser: this.$store.state.user.info.name,
      actionCreateUserId: this.$store.state.user.info.YtId,
      fileLists: [],
      userList: [],
      ifApprove: 1,
      bmwUserList: [],
    };
  },
  watch: {
    initBmwList: {
      handler() {
        this.getBmwUserList();
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.getBmwUserList("userList");
    this.getBmwUserList("bmwUserList");
  },
  methods: {
    moment,
    // 添加
    addInput() {
      // 新增一个新的数据初始化
      this.inputList.push({
        Id: +new Date(),
        ActionRemarkInfo: "",
        ActionCreatetime: moment().format("YYYY-MM-DD HH:mm:ss"),
        ActionCreateUserName: this.actionCreateUser,
        ActionCreateUser: this.actionCreateUserId,
      });
    },
    disabledDate(current) {
      let starttime = moment(
        this.form.getFieldValue("BreachActionStartTime") ?? ""
      );
      const currentDate = starttime.format("YYYY-MM-DD");
      return current && current.format("YYYY-MM-DD") < currentDate;
    },
    async deleteInput(Id) {
      if (Id > 1000000) {
        this.inputList = this.inputList.filter((item) => item.Id !== Id);
      } else {
        let { code } = await deleteRemark({ Id });
        if (code === 1) {
          this.inputList = this.inputList.filter((item) => item.Id !== Id);
        }
      }
    },
    //删除上传文件
    async delFile(file) {
      let { code } = await deleteRemark({ Id: file.uid });
      if (code === 1) {
        const index = this.fileLists.indexOf(file);
        this.fileLists.splice(index, 1);
        return true;
      }
      return false;
    },
    // 文件上传
    async handleChange(e) {
      // 上传提交
      let formdata = new FormData();
      formdata.append("file", e.file);
      try {
        const { status, data } = await axios({
          url: `${process.env.VUE_APP_BASE_API}/v1/oss/upload`,
          method: "post",
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
        });
        if (status == 200 && data.code == 1) {
          if (data.data != "") {
            await this.$nextTick();
            var files = data.data;
            var index = this.fileLists.length;
            if (files != "" && files != undefined) {
              var fileName = files.split("/");
              // 上传文件完成后新增
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.Url + data.data,
                ifNew: true,
                halfPath: data.data,
              });
            }
          }
        } else {
          this.$message.error(
            this.$t("user.verification-code.required111566110577282")
          );
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    async getBmwUserList(value, key) {
      const { data } = await getUserList({ UserEmail: value, UserName: value });
      this[key] = this.initBmwList.length
        ? [...this.initBmwList, ...data]
        : data;
    },
    async saveRemarkList(list = this.inputList) {
      let newRemark = []; // 新建的备注
      let changeRemark = []; // 修改的备注
      let deleteRemark = []; // 删除的备注
      list.forEach((item) => {
        if (item.ActionRemarkInfo) {
          let itemCopy = { ...item };
          if (!item.Id || item.Id > 1000000) {
            // 解决点确认后返显问题
            itemCopy.Id = undefined;
            itemCopy.ActionType = 1;
            itemCopy.ActionCreatetime = undefined;
            itemCopy.ActionCreateUser = undefined;
            itemCopy.ActionId = this.currentData.Id;
            newRemark.push(itemCopy);
          } else {
            itemCopy.ActionUploadUrl = undefined;
            changeRemark.push(itemCopy);
          }
        } else if (item.Id < 1000000) {
          deleteRemark.push(item);
        }
      });
      if (newRemark.length) {
        await createRemark(newRemark);
      }
      if (changeRemark.length) {
        await updateRemark(changeRemark);
      }
      if (deleteRemark.length) {
        deleteRemark.forEach((item) => {
          deleteRemark({
            Id: item.Id,
          });
        });
      }
    },
    getActionTitle(title) {
      if (!title) return false;
      switch (title) {
        case "result":
          return this.$t("breach.steps.step3.actionlist.result");
        case "back":
          return this.$t("breach.steps.step3.action.new.buttons.back");
        case "restart":
          return this.$t("breach.steps.step3.action.new.buttons.restart");
        default:
          return false;
      }
    },
  },
};
</script>

<style>
</style>